package com.clusterswisdom.horn.api.tmall.action.bill;

import java.util.Calendar;
import java.util.Date;
import java.util.LinkedList;
import java.util.List;

import com.alibaba.fastjson.JSONObject;
import com.clusterswisdom.horn.api.ioc.HornAction;
import com.clusterswisdom.horn.api.ioc.HornResponse;
import com.clusterswisdom.horn.api.ioc.api.ApiConfig;
import com.clusterswisdom.horn.api.tmall.TmallInstance;
import com.clusterswisdom.horn.api.tmall.action.AbstractTmallAction;
import com.taobao.api.domain.Bill;
import com.taobao.api.response.BillBillsGetResponse;
/**
 * 获取账期内所有账单(账期可以大于1天)
 * @author Jin_tian
 *
 */
public class GetBillsByDateAction extends AbstractTmallAction implements HornAction{
	
	@Override
	public HornResponse execute(ApiConfig config, JSONObject param) throws Exception {
		return new HornResponse(true, getDaysBills(param));
	}
	
	protected List<Bill> getDaysBills(JSONObject param) throws Exception {
		Calendar begin = getBeginDate(param);
		Calendar end = getEndDate(param);
		List<Bill> bills = new LinkedList<Bill>();
		
		while (begin.before(end)) {
			param.put("start_time", begin.getTime());
			begin.add(Calendar.DAY_OF_YEAR, 1);
			param.put("end_time", begin.getTime());
			
			int pageNo = 1;
			BillBillsGetResponse response = null;
			do {
				param.put("page_no", pageNo++);
				response = (BillBillsGetResponse)TmallInstance.getInstance().executeRequest(param, "bill", "billBillsGet");
				if(response.isSuccess() && response.getBills() != null && response.getBills().size() > 0){
					bills.addAll(response.getBills());
				}
				
			} while(response.getHasNext());
		}
		
		return bills;
	}
	
	private Calendar getBeginDate(JSONObject param) {
		Date begin = param.getDate("startTime");
		if (begin == null) {
			begin = new Date();
		}
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(begin);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		
		return calendar;
	}
	
	private Calendar getEndDate(JSONObject param) {
		Date end = param.getDate("lastTime");
		if (end == null) {
			end = new Date();
		} 
		
		Calendar calendar = Calendar.getInstance();
		calendar.setTime(end);
		calendar.set(Calendar.HOUR_OF_DAY, 0);
		calendar.set(Calendar.MINUTE, 0);
		calendar.set(Calendar.SECOND, 0);
		calendar.set(Calendar.MILLISECOND, 0);
		calendar.add(Calendar.DAY_OF_YEAR, 1);
		
		return calendar;
	}
}